package org.pada.client.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Type;

/**
 * @author shen.peng
 * @since 2024/9/13
 */
@Slf4j
public class JsonUtil {

    protected static final ObjectMapper MAPPER = new ObjectMapper();

    static {
        MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }


    public static <T> T convertObject(JsonNode data, Class<T> clazz) {
        try {
           return MAPPER.convertValue(data, clazz);
        } catch (IllegalArgumentException e) {
            log.error("convert data fail", e);
            throw new RuntimeException("convert data fail", e);
        }
    }

    public static <T> T parseObject(String data, Class<T> clazz) {
        try {
            return MAPPER.readValue(data, clazz);
        } catch (JsonProcessingException e) {
            log.error("parse data fail", e);
            throw new RuntimeException("parse data fail", e);
        }
    }

    public static <T> T parseObject(String data, TypeReference<T> typeReference) {
        try {
            return MAPPER.readValue(data, typeReference);
        } catch (JsonProcessingException e) {
            log.error("parse data fail", e);
            throw new RuntimeException("parse data fail", e);
        }
    }

    public static <T> T parseObject(String data, Type type) {
        try {
            return MAPPER.readValue(data, MAPPER.constructType(type));
        } catch (JsonProcessingException e) {
            log.error("parse data fail", e);
            throw new RuntimeException("parse data fail", e);
        }
    }

    public static String toJSONString(Object o) {
        try {
            return MAPPER.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            log.error("serialize data fail", e);
            throw new RuntimeException("serialize data fail", e);
        }
    }

    public static JsonNode parseJsonNode(Object object) {
        try {
            return MAPPER.valueToTree(object);
        } catch (IllegalArgumentException e) {
            log.error("convert data fail", e);
            throw new RuntimeException("convert data fail", e);
        }
    }
}
